package 枚举与尺聚法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class code82 {

    public static void main(String[] args) {
        List<List<Integer>> lists = combinationSum(new int[]{10,1,2,7,6,1,5}, 8);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        int[] isFlag = new int[candidates.length];
        dfs(0, candidates, isFlag, target, result, new Stack<Integer>());
        return result;

    }
    static void dfs(int start, int[] candidates, int[] isFlag, int target, List<List<Integer>> result, Stack<Integer> linkedList) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(linkedList));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && isFlag[i - 1] == 0) continue;
            if (isFlag[i] != 1) {
                isFlag[i] = 1;
                linkedList.push(candidates[i]);
                dfs(i + 1, candidates, isFlag, target - candidates[i], result, linkedList);
                isFlag[i] = 0;
                linkedList.pop();
            }
        }

    }
}
